import axios from 'axios';
import {message,notification} from 'antd';
import {locStorage} from './storage';
import {ERR_LOGIN_CODE} from '../config'

const isDev = process.env.NODE_ENV === 'development';

const as = axios.create({
        baseURL: isDev ? 'http://127.0.0.1:7001/api' : '/',
        // baseURL: isDev ? 'http://192.168.10.244:7001/api' : '/',

        withCredentials: true,
        headers: {},

        // 请求之后处理的数据
        transformResponse: [(data: any) => {
            if (ERR_LOGIN_CODE.indexOf(data.code) > -1) {
                locStorage('chasing_the_wind_info', null);
                return message.error(data.message, 3, () => {
                    window.location.reload();
                })
            }

            return data;
        }],

        // 响应数据格式
        responseType: 'json',

        // 超时处理  开发环境忽略超时
        timeout: isDev ? 1000000 : 8000

    }),
    handleRequest = ({type = 'get', url = '', option = {}, data = {}}): any => {
        try {
            console.group('------------API------------')
            console.log('method:', type);
            console.log('path:', url);
            console.log('body:', data);
            console.groupEnd();
            if (type === 'get') {
                return as.get(url, {params: option});
            } else {
                return as.post(url, data, option);
            }

        } catch (err) {
            notification.error({
                message: '请求错误',
                description: err
            });
            console.error(err);
        }
    };

// 响应拦截
as.interceptors.response.use((response) => {
    // Do something with response data
    return response.data;
}, (error) => {
    // Do something with response error
    return Promise.reject(error);
});
export default {
    get(url: string, option = {}) {
        return handleRequest({url, option});
    },
    post(url: string, data = {}, option = {}) {
        return handleRequest({
            url,
            option,
            data,
            type: 'post'
        });
    }
}
